import resources.Constants;

import registnet.dao.CollegePeer;
import registnet.dao.College;

CollegePeer collegePeer = new CollegePeer();
College college;

List data = new Vector();
List resultSet = new Vector();

boolean isShowingInfo;
boolean isSearching;

/* [start] 	initializes gui variables */
String _instance = bundle.getProperty("registnet.module.data_management.college");
String _instances = bundle.getProperty("registnet.module.data_management.colleges");

String _college_code = bundle.getProperty("registnet.module.data_management.macro.colleges.form.college_code");
String _college_name = bundle.getProperty("registnet.module.data_management.macro.colleges.form.college_name");
String _save = bundle.getProperty("registnet.module.data_management.macro.colleges.form.save");
String _cancel = bundle.getProperty("registnet.module.data_management.macro.colleges.form.cancel");

String _add = bundle.getProperty("registnet.module.data_management.actions.menu.add");
String _edit = bundle.getProperty("registnet.module.data_management.actions.menu.edit");
String _delete = bundle.getProperty("registnet.module.data_management.actions.menu.delete");
String _import = bundle.getProperty("registnet.module.data_management.actions.menu.import");
String _search = bundle.getProperty("registnet.module.data_management.actions.menu.search");
String _show_all = bundle.getProperty("registnet.module.data_management.actions.menu.show_all");

String _registrar = Constants.REGISTRAR;
String _college = Constants.COLLEGE;
String _unit = Constants.UNIT;

String _proceed = bundle.getProperty("registnet.messages.proceed");
String _check = bundle.getProperty("registnet.messages.check");
String _successful = bundle.getProperty("registnet.messages.successful");
String _failed = bundle.getProperty("registnet.messages.failed");
String _select_one = bundle.getProperty("registnet.messages.select_one");
String _selected = bundle.getProperty("registnet.messages.selected");
String _use_search_result_viewer = bundle.getProperty("registnet.messages.use_search_result_viewer");

String _icon_add = bundle.getProperty("registnet.icons.add");
String _icon_edit = bundle.getProperty("registnet.icons.edit");
String _icon_delete = bundle.getProperty("registnet.icons.delete");
String _icon_import = bundle.getProperty("registnet.icons.import");
String _icon_search = bundle.getProperty("registnet.icons.search");
String _icon_show_all = bundle.getProperty("registnet.icons.show_all");
/* [end] */


/* [start]	prepares the tree */
ArrayList alc = new ArrayList();
SimpleTreeNode root = new SimpleTreeNode("ROOT", alc);
/* [end] */

/* setting the user for logs */
if(_user_type.equals(_registrar))
	collegePeer.setUser(_user, _registrar);
else
	collegePeer.setUser(_user, _office);
/* [end] */

/* [start]	defines the renderer for the tree */
public class MyTreeitemRenderer implements TreeitemRenderer {
	public void render(Treeitem item, Object data) throws Exception {
		String str = (String)data.getData();
		Treerow tr = null;
		Treecell tc = new Treecell(str);
		if(item.getTreerow()==null){
			tr = new Treerow();
			tr.setParent(item);
		}else{
			tr = item.getTreerow(); 
			tr.getChildren().clear();
		}
		tc.setParent(tr);
		item.setOpen(false);
	}
}
/* [end] */



/* [start]	retrieves the colleges and places them on the tree; */
public void retrieveObjects(){
	alc.clear();
	data = new CollegePeer().getAllColleges();
	for(int i=0; i<data.size(); i++){
		SimpleTreeNode stnCollege = new SimpleTreeNode(data.get(i).getCollegeCode(), new ArrayList());
		alc.add(stnCollege);
	}
	SimpleTreeModel stm = new SimpleTreeModel(root);
	instance_tree.setModel(stm);
	instance_tree.setTreeitemRenderer(new MyTreeitemRenderer());
}
/* [end] */



/* [start]	shows all the entries */
void showAll(){
	retrieveObjects();
	try{
		title.setValue("");
		contents.removeChild(contents.getFirstChild());
	}catch(Exception e ){}
}
/* [end] */



/* [start]	defines an event listener for the items on the tree;
			when the item is selected, its info is displayed */
private class SelectEventListener implements EventListener {
	public SelectEventListener (){}
	public void onEvent(Event event) throws UiException {
		showInfo();
	}
}
/* [end] */



/* [start]	defines an event listener for the cancel button;
			when fired, it deselects the items on the tree */
private class CancelEventListener implements EventListener {
	public SubmitEventListener (){}
	public void onEvent(Event event) throws UiException {
		instance_tree.clearSelection();
		try{
			title.setValue("");
			contents.removeChild(contents.getFirstChild());
		} catch (Exception e) {}
	}
}
/* [end] */



/* [start]	defines an event listener for the search button */
private class SearchEventListener implements EventListener {
	public SearchEventListener (){}
	public void onEvent(Event event) throws UiException {
		int isConfirmed = Messagebox.show(_use_search_result_viewer, "", Messagebox.YES | Messagebox.NO, Messagebox.QUESTION);
		if (isConfirmed == Messagebox.YES){
			resultSet = collegePeer.searchCollege(college_code.value, college_name.value);
			showSearchResultViewer();
		}
		else
			returnSearchResults();
		try{
			title.setValue("");
			contents.removeChild(contents.getFirstChild());
		} catch (Exception e) {}
	}
}
/* [end] */



/* [start]	replaces the contents of the tree with the result set of the search */
void returnSearchResults(){
	alc.clear();
	resultSet = collegePeer.searchCollege(college_code.value, college_name.value);
	for(int i=0; i<resultSet.size(); i++){
		SimpleTreeNode stnCollege = new SimpleTreeNode(resultSet.get(i).getCollegeCode(), new ArrayList());
		alc.add(stnCollege);
	}
	instance_tree.setModel(instance_tree.getModel());
}
/* [end] */



/* [start] displays the info of the selected item */
void showInfo(){
	isShowingInfo = true;
	isSearching = false;
	if (contents.getFirstChild() != null){
		contents.removeChild(contents.getFirstChild());
	}
	try{
		if (instance_tree.getSelectedCount() == 1){
			college = collegePeer.getCollege(instance_tree.getSelectedItem().getLabel());
			Component show_instance_form = Executions.createComponents("/WEB-INF/macros/data_management/college_form.zul", contents, null);
			title.setValue(college.getCollegeCode());
			show_instance_form.getFellow("college_code_l").setValue(college.getCollegeCode());
			show_instance_form.getFellow("college_name_l").setValue(college.getCollegeName());
			show_instance_form.getFellow("save_btn").detach();
			show_instance_form.getFellow("cancel_btn").detach();
		}
		else if (instance_tree.getSelectedCount() > 1)
			title.setValue("" + instance_tree.getSelectedCount() + " " + _instance + " " + _selected);
		else
			title.setValue("");
	}catch (Exception e) { title.setValue(""); }
}
/* [end] */



/* [start]	displays the form for creating a new or editing an existing entry */
void showForm(String action){
	isShowingInfo = false;
	isSearching = false;
	try{
		contents.removeChild(contents.getFirstChild());
	} catch (Exception e) {}
	if (action.equals(_edit)){
		if(instance_tree.getSelectedCount() == 1){
			Component edit_instance_form = Executions.createComponents("/WEB-INF/macros/data_management/college_form.zul", contents, null);
			title.setValue(_edit + " " + college.getCollegeCode());
			edit_instance_form.getFellow("college_code").setValue(college.getCollegeCode());
			edit_instance_form.getFellow("college_name").setValue(college.getCollegeName());
			edit_instance_form.getFellow("save_btn").addEventListener("onClick", new SubmitEventListener(action));
			edit_instance_form.getFellow("cancel_btn").addEventListener("onClick", new CancelEventListener());
		}
		else{
			alert(_select_one + " " + _instance);
		}
	}	
	else if (action.equals(_add)){
		Component add_instance_form = Executions.createComponents("/WEB-INF/macros/data_management/college_form.zul", contents, null);
		title.setValue(_add + " " + _instance);
		instance_tree.clearSelection();
		add_instance_form.getFellow("save_btn").addEventListener("onClick", new SubmitEventListener(action));
		add_instance_form.getFellow("cancel_btn").addEventListener("onClick", new CancelEventListener());
	}
}
/* [end] */



/* [start]	displays the form for creating a new or editing an existing entry */
void importData(){
	List temp = new Vector();
	org.zkoss.util.media.Media media = Fileupload.get();
	if(media != null)
		temp = collegePeer.importColleges(media.getStringData());
	if(temp != null){
		data.addAll(temp);
		retrieveObjects();
		title.setValue(_import + " " + _instance + " " + _successful);
	}
}
/* [end] */



/* [start]	creates a new entry;
			updates the tree */
void createNewCollege(){
	
	if (isValid()){
		if (collegePeer.createNewCollege(college_code.value, college_name.value) != null){
			data.add(collegePeer.getCollege(college_code.value));
			title.setValue(_add + " " + _instance + " " + _successful);
			SimpleTreeNode stnCollege = new SimpleTreeNode(college_code.value, new ArrayList());
			alc.add(stnCollege);
			instance_tree.setModel(instance_tree.getModel());		
			try{
				contents.removeChild(contents.getFirstChild());
			} catch (Exception e) { }
		}
		else
			alert(_check);
	}
	else{
		alert(_check);
	}
}
/* [end] */



/* [start]	edits an existing entry;
			updates the tree */
void editCollege(){
	if (isValid()){
		try{
			if (collegePeer.updateCollege(collegePeer.getCollegeId(instance_tree.getSelectedItem().getLabel()), college_code.value, college_name.value)){
				data.set(instance_tree.getSelectedItem().indexOf(), collegePeer.getCollege(college_code.value));
				SimpleTreeNode stnCollege = new SimpleTreeNode(college_code.value, new ArrayList());
				alc.set(instance_tree.getSelectedItem().indexOf(), stnCollege);
				instance_tree.clearSelection();
				instance_tree.setModel(instance_tree.getModel());
				title.setValue(_edit + " " + _instance + " " + _successful);
			}
			try{
				contents.removeChild(contents.getFirstChild());
			} catch (Exception e) { }
		} catch (Exception e) { alert(_check); }
	}
	else{
		alert(_check);
	}
}
/* [end] */



/* [start]	deletes an entry */
void delete(){
	if(instance_tree.getSelectedCount() != 0){
		int isConfirmed = Messagebox.show(_proceed, _delete + " " + _instance, Messagebox.YES | Messagebox.NO, Messagebox.QUESTION);
		if (isConfirmed == Messagebox.YES){
			boolean isError = false;
			int errorCount = 0;
			Iterator i = instance_tree.getSelectedItems().iterator();
			int counter = 0;
			while(i.hasNext()){
				Treeitem treeitem = i.next(); 
				int temp = collegePeer.getCollegeId(treeitem.getLabel());
				if (collegePeer.deleteCollege(temp)){
					alc.remove(treeitem.indexOf() - counter);
					data.remove(treeitem.indexOf() - counter);
					counter++;
				}
				else{
					isError = true;
					errorCount++;
				}				
			}
			instance_tree.setModel(instance_tree.getModel());
			if (isError){ 
				alert(_delete + " " + _failed + ": " + errorCount + " " + _instance);
				title.setValue(_delete + " " + _instance + " " + _failed);
			}
			
			else{
				title.setValue(_delete + " " + _instance + " " + _successful);
				if (contents.getFirstChild() != null){
					contents.removeChild(contents.getFirstChild());
				}
			}
		}			
	}
	else{
		alert(_select_one + " " + _instance);
	}
}
/* [end] */



/* [start] validates the form */
boolean isValid(){
	if (college_code.value != null && college_code.value.trim().length() == 0)
		return false;
	if (college_name.value != null && college_name.value.trim().length() == 0)
		return false;
	return true;
}
/* [end] */



/* [start]	defines an event listener for the submit button */
private class SubmitEventListener implements EventListener {
	String submitType;
	public SubmitEventListener (String submitType){
		this.submitType = submitType; 
	}
	public void onEvent(Event event) throws UiException {
		if(this.submitType.equals(_add))
			createNewCollege();
		else if (this.submitType.equals(_edit))
			editCollege();
	}
}
/* [end] */



/* [start]	filters the contents of the listbox based on the
			what was entered by the user */
void filter(String string){
	ListIterator i = data.listIterator();
	alc.clear();
	while(i.hasNext()){
		String temp = i.next().getCollegeCode(); 
		if(temp.toUpperCase().startsWith(string.toUpperCase())){
			SimpleTreeNode stn = new SimpleTreeNode(temp, new ArrayList());
			alc.add(stn);
		}
	}
	instance_tree.setModel(instance_tree.getModel());
}
/* [end] */








void showSearchForm(){
	isSearching = true;
	isShowingInfo = false;
	try{
		contents.removeChild(contents.getFirstChild());
	} catch (Exception e) {}

	Component search_college_form = Executions.createComponents("/WEB-INF/macros/data_management/college_form.zul", contents, null);
	title.setValue(_search + " " + _instance);
	instance_tree.clearSelection();
	search_college_form.getFellow("search_btn").addEventListener("onClick", new SearchEventListener());
	search_college_form.getFellow("cancel_btn").addEventListener("onClick", new CancelEventListener());
}

void showSearchResultViewer(){
	Tab tab = new Tab("Search Result");
	Tabs tabs = stage.getTabs();
	tab.setClosable(true);
	tab.setParent(tabs);
	stage.setSelectedTab(tab);
		
	Tabpanel tabpanel = new Tabpanel();
	tabpanel.setSclass("background_light_blue");
	Tabpanels tabpanels = stage.getTabpanels();
	tabpanel.setParent(tabpanels);
	stage.setSelectedPanel(tabpanel);
	
	HashMap map = new HashMap();
	map.put("resultSet", resultSet);
	map.put("instance", _instance);
	
	Component search_result_viewer = Executions.createComponents("/WEB-INF/macros/data_management/search_result_viewer.zul", tabpanel, map);
	title.setValue(_search + " " + _instance);
}

